<template>
  <div class="ad-swiper">
    <draggable :list="sValue" v-bind="{ animation: 120, filter: 'input', preventOnFilter: false }">
      <div class="swiper-item" v-for="(item, index) in sValue" :key="index">
        <div class="ad-title">
          <a-icon class="drag" type="menu" />
          <span>广告位{{ index + 1 }}</span>
          <a-icon
            v-if="sValue.length > 1"
            class="delete"
            type="delete"
            @click="handleDelete(index)"
          />
        </div>
        <AdPicture v-model="sValue[index]" />
      </div>
      <div v-if="sValue.length < 10" class="data-add">
        <a-button icon="plus" @click="handleAddData()">添加广告位 (最多10个)</a-button>
      </div>
    </draggable>
  </div>
</template>

<script>
import draggable from 'vuedraggable'
import { cloneDeep } from 'lodash'
import PropTypes from 'ant-design-vue/es/_util/vue-types'
import { SelectImage } from '@/components'
import AdPicture from './AdPicture'

// 默认广告图数据
const defaultData = { imageUrl: null, link: null }

export default {
  components: { SelectImage, draggable, AdPicture },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    // 当前选中项的value
    value: PropTypes.any,
  },
  data () {
    return {
      sValue: {
        adList: [{ imageUrl: null, link: null }],
        interval: 3
      }
    }
  },
  watch: {
    value: {
      // 首次加载的时候执行函数
      immediate: true,
      handler (val) {
        if (val) {
          this.sValue = val
        }
      }
    },
    sValue: {
      deep: true,
      handler (val) {
        console.log('sValue Sw', val)
        this.$emit('change', val)
      }
    },
  },
  methods: {

    // 新增数据
    handleAddData () {
      this.sValue.push(cloneDeep(defaultData))
    },

    // 删除元素
    handleDelete (index) {
      this.sValue.splice(index, 1)
    }

  }
}
</script>

<style lang="less" scoped>
.ad-swiper {
  width: 600px;
}
.swiper-item {
  margin-bottom: 15px;
  background-color: #f7f8fa;
  &:last-child {
    margin-bottom: 0;
  }
}
.ad-title {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #edeef2;
  padding: 0 18px;
  .drag {
    cursor: move;
    margin-right: 12px;
  }
  .delete {
    cursor: pointer;
    margin-left: auto;
  }
}

// 新增数据
.data-add {
  margin-top: 10px;

  button {
    width: 100%;
    color: @primary-color;
    height: 40px;
    border-radius: 5px;
    font-size: 12px;
    // border-color: #cccccc21;

    &:hover {
      border-color: @primary-color;
    }
  }
}
</style>
